package com.tsing.cedap.common.config;

import cn.hutool.jwt.JWT;
import com.tsing.cedap.common.annotations.PassToken;
import com.tsing.cedap.common.constants.AuthConstant;
import com.tsing.cedap.common.exceptions.BusinessException;
import com.tsing.cedap.common.exceptions.CommonException;
import com.tsing.cedap.common.utils.GetLoginUserUtil;
import com.tsing.cedap.common.vo.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.nio.charset.StandardCharsets;

public class JwtInterceptor implements HandlerInterceptor {

    @Value("${frame.auth.support:false}")
    private String authSupport;

    @Autowired
    private RedisManager redisManager;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        if (!"true".equals(authSupport)) {
            return true;
        }
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        if (method.isAnnotationPresent(PassToken.class)) {
            return true;
        }
        String token = request.getHeader(AuthConstant.AUTHENTICATION_HEAD);
        UserVo userVo = GetLoginUserUtil.getLoginUserInfo(token, redisManager);
        try {
            if (!JWT.of(token).setKey(userVo.getId().getBytes(StandardCharsets.UTF_8)).verify()) {
                throw new BusinessException(CommonException.Proxy.TOKEN_VERIFY_ERROR);
            }
        } catch (Exception e) {
            throw new BusinessException(CommonException.Proxy.TOKEN_VERIFY_ERROR);
        }
        //将user信息存到redis
        redisManager.resetStringExpire(userVo.getToken(), userVo.getExpire());
        //将token存到redis
        redisManager.resetStringExpire(AuthConstant.USER_TOKEN_PREFIX + userVo.getId(), userVo.getExpire());
        return true;
    }

}
